<template>
  <div class="modal-wrap">
    <a-form-model
      layout="horizontal"
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 18 }"
      class="content"
    >
      <a-form-model-item
        v-for="(item, index) in formKey"
        :key="index"
        :label="item.title"
        :prop="item.key"
      >
        <template v-if="item.view === 'sel_search'">
          <a-select
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            show-search
            placeholder="请选择"
            option-filter-prop="children"
            style="width: 100%"
            :filter-option="filterOption"
            @change="(e) => onChange(e, item.key)"
          >
            <a-select-option
              v-for="key in option"
              :key="key.id"
              :value="key.roleCode"
            >
              {{ key.roleName }}
            </a-select-option>
          </a-select>
        </template>
        <template v-else-if="item.view === 'datetime'">
          <a-date-picker
            show-time
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            format="YYYY-MM-DD HH:mm:ss"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            placeholder="请选择"
            @change="(e) => onChange(e, item.key)"
          />
        </template>
        <template v-else-if="item.view === 'cat_tree'">
          <a-tree-select
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            style="width: 100%"
            :tree-data="topClassRoleList"
            placeholder="请选择"
            :maxTagCount="1"
            treeDefaultExpandAll
            treeCheckable
            treeCheckStrictly
            treeNodeFilterProp="title"
            @change="(val) => selectTreeChange(val, item.key)"
          ></a-tree-select>
        </template>
        <template v-else-if="item.view === 'cat_tree_auth'">
          <a-tree-select
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            style="width: 100%"
            :tree-data="treeData"
            placeholder="请选择"
            treeCheckable
            treeCheckStrictly
            treeNodeFilterProp="title"
            @change="
              (val, _, extra) => selectTreeChangeAuth(val, extra, item.key)
            "
          ></a-tree-select>
        </template>
        <template v-else-if="item.view === 'radio'">
          <a-radio-group
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
          >
            <a-radio value="0">正常</a-radio>
            <a-radio value="1">冻结</a-radio>
          </a-radio-group>
        </template>
        <template v-else-if="item.view === 'textarea'">
          <a-textarea
            :disabled="disableStatus(item.key)"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
            :autoSize="{ minRows: 2, maxRows: 4 }"
          />
        </template>
        <template v-else-if="item.view === 'passWord'">
          <a-input-password
            :disabled="disableStatus(item.key)"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
          ></a-input-password>
        </template>
        <template v-else-if="item.view === 'text_number'">
          <a-input-number
            :disabled="disableStatus(item.key)"
            :min="1"
            style="width: 100%"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e, item.key)"
          ></a-input-number>
        </template>
        <template v-else>
          <a-input
            :disabled="disableStatus(item.key)"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
          ></a-input>
        </template>
      </a-form-model-item>
    </a-form-model>
    <div class="my-btn" v-show="!disable">
      <a-button type="primary" @click="submit">保存</a-button>
      <a-button @click="offModal">取消</a-button>
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from "vue";
import { checkRoleCode } from "@/services/roleManage.service";

const topClassRoleList = [
  {
    title: "系统管理员",
    key: "systemAdmin",
    value: "systemAdmin",
    children: [
      {
        title: "开发人员",
        key: "developAdmin",
        value: "developAdmin",
      },
    ],
  },
]; //功能权限页面
const props = defineProps({
  formKey: {
    type: Array,
  },
  option: {
    type: Array,
  },
  treeData: {
    type: Array,
  },
  allSelectList: {
    type: Array,
  },
  formData: {
    type: Object,
  },
  title: {
    type: String,
  },
  tableName: {
    type: String,
  },
  editNameBack: {
    type: String,
  },
  disable: {
    type: Boolean,
    default: false,
  },
});
const ruleForm = ref(null);
const emit = defineEmits([
  "updateFormData",
  "offModalOperation",
  "submitModal",
]);
function disableStatus(key) {
  let status = props.disable;
  if (key === "createTime") {
    status = true;
  } else if (key === "createBy") {
    status = true;
  }
  return status;
}
function onChange(value, key) {
  emit("updateFormData", key, value);
}

function selectTreeChange(value, key) {
  if (value.length > 1) {
    emit("updateFormData", key, []);
    setTimeout(() => {
      emit("updateFormData", key, value.slice(1));
    }, 300);
    if (value.slice(1).some((item) => item.value === "systemAdmin")) {
      emit("updateFormData", "permissionIds", []);
      setTimeout(() => {
        emit("updateFormData", "permissionIds", props.allSelectList);
      }, 300);
    } else if (value.slice(1).some((item) => item.value === "developAdmin")) {
      emit("updateFormData", "permissionIds", []);
      setTimeout(() => {
        emit(
          "updateFormData",
          "permissionIds",
          props.allSelectList.slice(0, 4)
        );
      }, 300);
    }
  } else {
    if (value.some((item) => item.value === "systemAdmin")) {
      emit("updateFormData", "permissionIds", []);
      setTimeout(() => {
        emit("updateFormData", "permissionIds", props.allSelectList);
      }, 300);
    } else if (value.some((item) => item.value === "developAdmin")) {
      emit("updateFormData", "permissionIds", []);
      setTimeout(() => {
        emit(
          "updateFormData",
          "permissionIds",
          props.allSelectList.slice(0, 4)
        );
      }, 300);
    }
    emit("updateFormData", key, []);
    setTimeout(() => {
      emit("updateFormData", key, value);
    }, 300);
  }
}
const obj = {
  dimensionManagement: {
    label: "维度管理",
    value: "dimensionManagement",
  },
  dimensionValueManagement: {
    label: "维值管理",
    value: "dimensionValueManagement",
  },
  basicIndexManagement: {
    label: "基础指标管理",
    value: "basicIndexManagement",
  },
  userManage: {
    label: "用户管理",
    value: "userManage",
  },
  roleManage: {
    label: "角色管理",
    value: "roleManage",
  },
  indexManagement: {
    label: "角色管理",
    value: "indexManagement",
  },
};
//功能权限操作逻辑
function selectTreeChangeAuth(value, extra, key) {
  emit("updateFormData", key, value);
}
function filterOption(input, option) {
  return (
    option.componentOptions.children[0].text
      .toLowerCase()
      .indexOf(input.toLowerCase()) >= 0
  );
}
async function checkName(value, callback) {
  let params = {
    roleCode: value,
  };
  await checkRoleCode(params).then((res) => {
    if (res.code !== 0) {
      callback(new Error("角色校验失败"));
    } else {
      if (res.success) {
        return true;
      } else {
        callback(new Error("角色名称已存在"));
      }
    }
  });
}
async function validateKpiCode(rule, value, callback) {
  if (value) {
    // 这里要区分新增额编辑操作。编辑的时候要做名称备份，允许不修改名称
    if (props.title.includes("修改")) {
      if (props.editNameBack === value) {
        return true;
      } else {
        await checkName(value, callback);
      }
    } else {
      await checkName(value, callback);
    }
  } else {
    callback(new Error("请输入"));
  }
}
const rules = computed(() => {
  let obj = {};
  if (props.formKey.length > 0) {
    if (!props.title.includes("查看")) {
      props.formKey.forEach((item, index) => {
        if (item.view === "text") {
          if (index === 0) {
            obj[item.key] = [
              { required: true, validator: validateKpiCode, trigger: "blur" },
            ];
          } else {
            obj[item.key] = [
              { required: true, message: "请输入", trigger: "change" },
            ];
          }
        } else if (item.view === "cat_tree") {
          obj[item.key] = [
            { required: true, message: "请选择", trigger: "blur" },
          ];
        } else if (item.view === "cat_tree_auth") {
          obj[item.key] = [
            { required: false, message: "请选择", trigger: "blur" },
          ];
        } else {
          obj[item.key] = [
            { required: true, message: "请选择", trigger: "change" },
          ];
        }
      });
    } else {
      props.formKey.forEach((item) => {
        obj[item.key] = [
          { required: false, message: "请选择", trigger: "change" },
        ];
      });
    }
  }
  return obj;
});
function submit(e) {
  e.preventDefault();
  ruleForm.value.validate((valid) => {
    if (valid) {
      emit("submitModal");
    }
  });
}
function offModal() {
  emit("offModalOperation");
}
</script>
<style scoped lang="less">
.modal-wrap {
  width: 100%;
  .my-btn {
    width: 100%;
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 40px;
  }
}
/deep/ .ant-row.ant-form-item.ant-form-item-with-help {
  margin-bottom: 0;
}
/deep/ .ant-row.ant-form-item {
  margin-bottom: 22px;
}
</style>
<style>
.ant-select-dropdown {
  max-height: 500px !important;
}
.ant-select-dropdown::-webkit-scrollbar {
  width: 7px;
}
.ant-select-dropdown::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: #c1c1c1;
}
</style>
